﻿using System.IO;

namespace Azure.Online.Proxy.Server {
    public class HttpServerResponse : HttpServerMessage {
        private readonly HttpServerContext _context;
        private readonly Stream _stream;
        private Stream _outputStream;

        public HttpServerResponse(HttpServerContext context, Stream stream) {
            _context = context;
            _stream = stream;
            Version = "HTTP/1.1";
        }

        public int StatusCode { get; set; }

        public string StatusDescription { get; set; }

        public string Version { get; set; }

        public Stream OutputStream {
            get {
                if (_outputStream == null) {
                    SendHeaders();
                    if (SendChunked) {
                        _outputStream = new HttpServerChunkedResponseStream(_context, _stream);
                    } else {
                        _outputStream = new HttpServerResponseStream(_context, _stream, ContentLength.Value);
                    }
                }
                return _outputStream;
            }
        }

        private void SendHeaders() {
            var mem = new MemoryStream();
            var writer = new StreamWriter(mem);
            writer.WriteLine("{0} {1} {2}", Version, StatusCode, StatusDescription);
            foreach (var header in Headers.Keys) {
                writer.WriteLine("{0}: {1}", header, Headers[header]);
            }
            writer.WriteLine();
            writer.Flush();
            var array = mem.ToArray();
            _stream.Write(array, 0, array.Length);
        }
    }
}
